package com.assets.Check;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.le.ScanCallback;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.assets.CanniBalize.NewCheck_allot;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Check.newTanWanCheck.NewCheck_alter;
import com.assets.Ip_set.Url;
import com.assets.Maintain.Maintain_data;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.bean.Input_item1;
import com.assets.bean.Issued_bean;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.CheckData;
import com.assets.util.DataCompressionExample;
import com.assets.util.IdWorkerUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.MyRFIDHandle;
import com.assets.util.NetworkUtil;
import com.assets.util.PlaySoundUtil;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.assets.util.ThreadPool;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.jjh.CheckDetailResult;
import com.jjh.TAssetAsset;
//import com.lckj.lcrrgxmodule.factory.ILcUhfProduct;
//import com.lckj.lcrrgxmodule.factory.LcModule;
//import com.rfid.PowerUtil;
import com.rfid.trans.ReadTag;
import com.rfid.trans.TagCallback;
import com.ubx.usdk.USDKManager;
import com.ubx.usdk.rfid.RfidManager;
import com.ubx.usdk.rfid.aidl.IRfidCallback;
import com.ubx.usdk.util.SoundTool;

//import com.lckj.lcrrgxmodule.factory.ILcUhfProduct;
//import com.lckj.lcrrgxmodule.factory.LcModule;
//import com.rfid.PowerUtil;
//import com.rfid.trans.ReadTag;
//import com.rfid.trans.TagCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.HttpURLConnection;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.core.Scheduler;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2019/1/22.
 * 作者：张志豪
 *
 * 盘点页面  有读卡页面
 *
 */

public class Check extends BaseActivity1 {
    private float versionCode = 0;
    private String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    private ScanCallback callback;
    private static final String TAG = "我爱你";
    private String checkDetailIds, isEdit = "";//单号，状态
    private RecyclerView recyclerView;
    private Button scan, submit;//扫码，上传,rfid
    private String id;
    private static final int R50KEYCODE = 523;

    private Boolean flag = false;
    private Button add_remark;

    private String checkDetailQueryById = "http://" + Url.IP + "/api/checkdetailQueryByIds";

    private String update  = "http://" + Url.IP + "/api/asstesUpdata";
    private String query_url = "http://" + Url.IP + "/api/checkAssetScanQuery";
    private LoadingDialog loadingDialog;
    private List<String> assetNumbers = new ArrayList<>();
    private String url = "http://" + Url.IP + "/api/checkdetailQueryByIds";
    private String upload_url = "http://" + Url.IP + "/api/assetCheck";
    private String add_br = "http://" + Url.IP + "/api/checkTextAdd";
    private List<TAssetAsset> For_data = new ArrayList<>();
    private List<TAssetAsset> Have_data = new ArrayList<>();
    private List<TAssetAsset> profit_data = new ArrayList<>();
    private List<TAssetAsset> losses_data = new ArrayList<>();
    private List<TAssetAsset> dataList = new ArrayList<>();
    private CheckAdapter adapter = new CheckAdapter(dataList);
    private EditText et_num;
    private static String devport = "/dev/ttyS3";//蓝畅
//    private ILcUhfProduct iLcUhfProduct;

    private TextView odd, createuser, sum, createdate, date;//盘点单号，创建人，应盘总数，创建日期，完成日期
    private TextView For_inventory, Have_inventory, inventory_profit, inventory_losses;//待盘点，已盘点，盘盈，盘亏
    private int star = 0;
    private String deptId = "";
    private String jifang;
    private String jigui;
    private String state;
    private Button btn_rfid;
    private LinearLayout losses;
    private LinearLayout profit;
    private LinearLayout aFor;
    private LinearLayout have;
    private ImageView imageView;
    private List<TAssetAsset> tAssList;
    private Map<String, String> map1 = new HashMap<>();;
    private MediaPlayer mediaPlayer;
    private SoundPool soundPool;


    //关闭读卡模块
//    private void close() {
//        PowerUtil.power("0");
//        iLcUhfProduct.DisConnect();
//    }

    public int readerType = 0;


    public  boolean RFID_INIT_STATUS = false;
    private static HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();


    public RfidManager mRfidManager;


    private final int MSG_UPDATE_UI = 0;
    private final int MSG_STOP_INVENTORY=1;


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_UPDATE_UI:
//                    scanListAdapterRv.notifyDataSetChanged();
                    handlerUpdateUI();
                    break;
                case MSG_STOP_INVENTORY:
//                    scanListAdapterRv.notifyDataSetChanged();
                    mHandler.removeCallbacksAndMessages(null);
                    if (btn_rfid.getText().equals("结束读取")){
                        btn_rfid.setText("开始读取");
                    }
                    break;
            }

        }
    };
    private Map<String, String> deduplication = new HashMap<>();


    private void handlerUpdateUI() {
        if (mHandler!=null){
            mHandler.sendEmptyMessageDelayed(MSG_UPDATE_UI,500);
        }
    }

    private void handlerStopUI() {
        if (mHandler!=null){
            mHandler.sendEmptyMessageDelayed(MSG_STOP_INVENTORY,200);
        }
    }


    private void setScanStatus(boolean isScan) {

        if (isScan) {
            Log.v(TAG,"--- startInventory()   ----");
            handlerUpdateUI();
            mRfidManager.startInventory((byte) 0);
//            mActivity.mRfidManager.startRead();//少量标签盘点建议使用：0；盘点标签超过 100-200建议使用：1.
        } else {
            Log.v(TAG,"--- stopInventory()   ----");
            mRfidManager.stopInventory();
            handlerStopUI();
        }
    }

    //初始化读卡
    private void initRfid() {


//        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
//        soundMap.put(1, soundPool.load(this, R.raw.msg, 1));



//        showToast("加载读卡模块总，请稍等");
//
//        try {
//            Thread.sleep(1500);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

//        MsgCallback callback = new MsgCallback();
//        iLcUhfProduct.SetCallBack(callback);//读取标签的回调
//        iLcUhfProduct.setsoundid(soundMap.get(1), soundPool);
        btn_rfid.setOnClickListener(v -> {

            Log.d(TAG, "点击了一下读卡按钮");

            if (RFID_INIT_STATUS) {
                if (btn_rfid.getText().equals("开始读取")) {
                    setCallback();
                    btn_rfid.setText("结束读取");
                    setScanStatus(true);
                } else {
                    btn_rfid.setText("开始读取");
                    setScanStatus(false);
                }
            }else {
                Log.d(TAG, "scanStartBtn  RFID未初始化 "  );
//                Toast.makeText(this,"RFID Not initialized",Toast.LENGTH_SHORT).show();
            }

//            String rfidTitle = btn_rfid.getText().toString();
//            if (rfidTitle.equals("开始读取")) {
//
//                if (iLcUhfProduct != null) {
//                    // 初始化 MediaPlayer
//                    mediaPlayer = MediaPlayer.create(this, R.raw.msg);
//                    iLcUhfProduct.StartRead();
//                    btn_rfid.setText("停止读取");
//                }else {
//                    initRfid();
//                    mediaPlayer = MediaPlayer.create(this, R.raw.msg);
//                    iLcUhfProduct.StartRead();
//                    btn_rfid.setText("停止读取");
//                }
//
//            } else {
//                if (mediaPlayer != null) {
//                    mediaPlayer.stop();
////                    mediaPlayer = null;
//                }
//                iLcUhfProduct.StopRead();
//                btn_rfid.setText("开始读取");
//            }


        });

    }

    public void setCallback(){
        if (mRfidManager!=null) {

            if (callback == null){
                callback = new ScanCallback();
            }
            mRfidManager.registerCallback(callback);
        }
    }

    class ScanCallback implements IRfidCallback {
        @Override
        public void onInventoryTag(String EPC, final String TID, final String strRSSI) {
//            epc:1111    tid:E280110520007351E531098E
            notiyDatas(EPC,TID,strRSSI);
            Log.e(TAG, "onInventoryTag:............... epc:"+EPC+"    tid:"+TID);

        }

        /**
         * 盘存结束回调(Inventory Command Operate End)
         */
        @Override
        public void onInventoryTagEnd()  {
            Log.d(TAG, "onInv entoryTagEnd()");
        }
    }

//    public class MsgCallback implements TagCallback {
//
//        @Override
//        public void tagCallback(ReadTag readTag) {
//
//            if (readTag != null) {
//                // 播放声音
//                mediaPlayer.start();
//
//                String epc = readTag.epcId.toUpperCase();
//
////                iLcUhfProduct.playSound();
//                if (!map1.containsKey(epc)) {
//                    readRfid(epc);
//                }
//
//            }
//        }
//
//        @Override
//        public int tagCallbackFailed(int i) {
//            return 0;
//        }
//
//        @Override
//        public int CRCErrorCallBack(int i) {
//            return 0;
//        }
//
//        @Override
//        public void FinishCallBack() {
//
//        }
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        newSubmit();
        canDialog();
//        close();

    }

    private void readRfid(String epc) {
        map1.put(epc, "");
//        2024010611370521
        try {
            epc = epc.substring(0, 14);
        }catch (Exception e) {

            e.printStackTrace();
        }
        


        if (For_data.size() == 0) {

            readOne(epc);


        }else {

            for (int i = 0; i < For_data.size(); i++) {

                if (epc.equals(For_data.get(i).getRfid())) {
                    For_data.get(i).setCheckResult("0");
                    For_data.get(i).setConcreteNum(For_data.get(i).getPlanNum());
                    Have_data.add(For_data.get(i));
                    For_data.remove(i);
                    runOnUiThread(() -> {
                        dataList.clear();
                        dataList.addAll(For_data);
                        adapter.notifyDataSetChanged();
                    });

                }else {
                    readTwo(epc);

                }
            }

        }


        if (losses_data.size() > 0) {

            for (int i = 0; i < losses_data.size(); i++) {

                if (epc.equals(losses_data.get(i).getRfid())) {
                    losses_data.get(i).setConcreteNum(losses_data.get(i).getPlanNum());
                    losses_data.get(i).setCheckResult("0");
                    Have_data.add(losses_data.get(i));
                    losses_data.remove(i);
                }else {

                    readThree(epc);

                }


            }


        }

        runOnUiThread(() -> {
            //待盘点的数量
            For_inventory.setText(For_data.size() + "");
            //已经盘点的数量
            Have_inventory.setText(Have_data.size() + "");
            //盘盈的数量
            inventory_profit.setText(profit_data.size() + "");
            //盘亏的数量
            inventory_losses.setText(losses_data.size() + "");

//            dataList.addAll(For_data);
//
//            adapter.notifyDataSetChanged();
        });


    }

    private void readThree(String epc) {
        Log.d("这个是蒋剑华的日志", "epc3: " + epc);
        if (deduplication.containsKey(epc)) {
            return;
        }
        deduplication.put(epc, "");

        Map<String, String> map = new HashMap<>();
        map.put("checkId", id);
        map.put("rfid", epc);
        map.put("assetNumber", "");


        NetworkUtil.rfidProfit(Url.myHttp(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                        try {
                            String result = responseBody.string();

                            if (result == null || result.isEmpty() || result.equals("{}")) {
                                return;
                            }

                            TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);
//                            TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);
                            List<String> quchong = new ArrayList<>();

                            for (TAssetAsset profit_datum : profit_data) {
                                if (quchong.contains(profit_datum.getRfid())) {
                                    return;
                                }
                            }
//                            for (TAssetAsset profit_datum : profit_data) {
//                                if (profit_datum.getAssetNumber().equals(tAssetAssets.getAssetNumber())) {
//                                    return;
//                                }
//
//                            }

                            profit_data.add(tAssetAssets);

                            runOnUiThread(() -> {
                                adapter.notifyDataSetChanged();
                            });
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void readTwo(String epc) {
        Log.d("这个是蒋剑华的日志", "epc2: " + epc);
        if (deduplication.containsKey(epc)) {
            return;
        }
        deduplication.put(epc, "");

        Map<String, String> map = new HashMap<>();
        map.put("checkId", id);
        map.put("rfid", epc);
        map.put("assetNumber", "");

        NetworkUtil.rfidProfit(Url.myHttp(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                        
                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                        try {
                            String result = responseBody.string();
                            Log.d(TAG, "result: " + result);
                            Log.d(TAG, "requestSuccess: " + "成功");
                            if (result == null || result.isEmpty() || result.equals("{}")) {
                                return;
                            }
                            TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);

                            List<String> quchong = new ArrayList<>();

                            for (TAssetAsset profit_datum : profit_data) {
                                if (quchong.contains(profit_datum.getRfid())) {
                                    return;
                                }
                            }
                            tAssetAssets.setUserId(Since_case.getInstance().getUserId());
                            profit_data.add(tAssetAssets);
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

//        MyOkHttp.getInstance().post(checkDetailQueryById, map, new MyOkHttp.requestMessage() {
//            @Override
//            public void requestFail() {
//                Log.d(TAG, "requestFail: " + "失败了");
//            }
//
//            @Override
//            public void requestComplete() {
//
//            }
//
//            @Override
//            public void requestSuccess(Response response) throws IOException {
////                        profit_data.clear();
//                String result = response.body().string();
//                Log.d(TAG, "result: " + result);
//                Log.d(TAG, "requestSuccess: " + "成功");
//                if (result == null || result.isEmpty() || result.equals("{}")) {
//                    return;
//                }
//                TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);
//                List<String> quchong = new ArrayList<>();
//
//                for (TAssetAsset profit_datum : profit_data) {
//                    if (quchong.contains(profit_datum.getRfid())) {
//                        return;
//                    }
//                }
//                tAssetAssets.setUserId(Since_case.getInstance().getUserId());
//                profit_data.add(tAssetAssets);
//
////                            Log.d(TAG, "profit_data: " + new Gson().toJson(profit_data));
//
//
//            }
//        });
    }

    private void readOne(String epc) {
        Log.d("这个是蒋剑华的日志", "epc1: " + epc);
        if (deduplication.containsKey(epc)) {
            return;
        }
        deduplication.put(epc, "");

        Map<String, String> map = new HashMap<>();
        map.put("checkId", id);
        map.put("rfid", epc);
        map.put("assetNumber", "");
        
        NetworkUtil.rfidProfit(Url.myHttp(), map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                        try {
                            String result = responseBody.string();
                            Log.d(TAG, "result: " + result);
                            Log.d(TAG, "requestSuccess: " + "成功");
                            if (result == null || result.isEmpty() || result.equals("{}")) {
                                return;
                            }
                            TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);

                            List<String> quchong = new ArrayList<>();

                            for (TAssetAsset profit_datum : profit_data) {
                                if (quchong.contains(profit_datum.getRfid())) {
                                    return;
                                }
                            }
                            tAssetAssets.setUserId(Since_case.getInstance().getUserId());
                            profit_data.add(tAssetAssets);

                            Log.d(TAG, "profit_data: " + new Gson().toJson(profit_data));

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_main);


        deptId = getIntent().getStringExtra("createDate");
//        LogUtils.d("createDate" + deptId);


        initRFID();
        initView();
        initRfid();



//        if (flag) {
//            ThreadPool.runThread(() -> {
//                PowerUtil.power("1");
//                iLcUhfProduct = new LcModule(this).createProduct(0x20);
//                iLcUhfProduct.Connect(devport, 115200);
//                iLcUhfProduct.SetRfPower(33);
//                initRfid();
//            });
//        }





//        new Thread(() -> {
//
//        }).start();
//
//
//
//        new Thread(() -> {
//
//        }).start()
//
//

//
        setWaitData();
//
//        runOnUiThread(() -> {
//            initRfid();
//
//            add_remark.setOnClickListener(v -> {
//                MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Check.this).builder()
//                        .setTitle("请填写备注")
//                        .setEditText("");
//                myAlertInputDialog.setPositiveButton("确认", v12 -> {
//                    add_remarks(myAlertInputDialog.getResult());
//                    myAlertInputDialog.dismiss();
//                }).setNegativeButton("取消", v1 -> myAlertInputDialog.dismiss());
//                myAlertInputDialog.show();
//            });
//            scan.setOnClickListener(v -> {
//                startQrCode();
//                LogUtils.d("调用扫码");
//            });
//
//            submit.setOnClickListener(v -> new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Check.this, AlertView.Style.Alert, new OnItemClickListener() {
//                @Override
//                public void onItemClick(Object o, int position) {
//
//                    //取消：position=-1,确定 position=0
//                    if (position == 0) {
//                        newSubmit();
//                    }
//                }
//            }).setCancelable(true).show());
//
//            initViewModel();
//        });


        initViewModel();
    }


    private void initRFID() {
        USDKManager.getInstance().init(this,new USDKManager.InitListener() {
            @Override
            public void onStatus(USDKManager.STATUS status) {
                if (status == USDKManager.STATUS.SUCCESS) {
                    Log.d(TAG, "initRfid()  success.");
                    RFID_INIT_STATUS = true;
                    mRfidManager = USDKManager.getInstance().getRfidManager();
                    readerType =  mRfidManager.getReaderType();//80为短距，其他为长距

                    Log.d(TAG, "initRfid: GetReaderType() = " +readerType );
                }else {
                    Log.d(TAG, "initRfid  fail.");
                }
            }
        });
    }

    private void initViewModel() {
        adapter.setPlac(new CheckAdapter.plac() {
            @Override
            public void onClickListener(int position) {

                final Dialog dialog = new Dialog(Check.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
                dialog.setContentView(R.layout.custom_dialog_layout); // 设置自定义布局
                dialog.setCancelable(true); // 设置是否可取消

                // 获取对话框的窗口对象
                Window window = dialog.getWindow();
                if (window != null) {
                    WindowManager.LayoutParams layoutParams = window.getAttributes();

                    // 设置对话框的宽度和高度
                    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;; // 宽度为300dp
                    layoutParams.height = 400; // 高度自适应内容

                    // 将布局参数应用到窗口
                    window.setAttributes(layoutParams);
                }
                // 显示弹窗
                dialog.show();
                EditText lou = dialog.findViewById(R.id.set_title);
                Button ok = dialog.findViewById(R.id.ok);
                Button no = dialog.findViewById(R.id.no);

                no.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                ok.setOnClickListener(v -> {

//                    dataList.get(position).setDivision(lou.getText().toString().trim()); //位置
                    dataList.get(position).setCompany(lou.getText().toString().trim());
                    List<TAssetAsset> dataList1 = new ArrayList<>();
                    dataList1.add(dataList.get(position));
                    Map<String, String> map = new HashMap<>();
                    map.put("data", new Gson().toJson(dataList1));


                    NetworkUtil.updatePlace(Url.myHttp(), map)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<ResponseBody>() {
                                @Override
                                public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                                }

                                @Override
                                public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                                    adapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                                    showToast("连接超时，请联系开发人员");
                                }

                                @Override
                                public void onComplete() {

                                }
                            });

                    dialog.dismiss();
                });

//                    MyOkHttp.getInstance().post(update, map, new MyOkHttp.requestMessage() {
//                        @Override
//                        public void requestFail() {
//                            showToast("连接超时，请联系开发人员");
//                        }
//
//                        @Override
//                        public void requestComplete() {
//
//                        }
//
//                        @Override
//                        public void requestSuccess(Response response) throws IOException {
//                            runOnUiThread(() -> {
//                                adapter.notifyDataSetChanged();
//                            });
//                        }
//                    });
//
//                    dialog.dismiss();
//                });





            }
        });

        adapter.setPlac1(new CheckAdapter.plac55() {
            @Override
            public void onClickListener(int position) {
                final Dialog dialog = new Dialog(Check.this);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
                dialog.setContentView(R.layout.custom_dialog_layout1); // 设置自定义布局
                dialog.setCancelable(true); // 设置是否可取消

                // 获取对话框的窗口对象
                Window window = dialog.getWindow();
                if (window != null) {
                    WindowManager.LayoutParams layoutParams = window.getAttributes();

                    // 设置对话框的宽度和高度
                    layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;; // 宽度为300dp
                    layoutParams.height = 400; // 高度自适应内容

                    // 将布局参数应用到窗口
                    window.setAttributes(layoutParams);
                }
                // 显示弹窗
                dialog.show();
                EditText lou = dialog.findViewById(R.id.set_title);
                Button ok = dialog.findViewById(R.id.ok);
                Button no = dialog.findViewById(R.id.no);

                no.setOnClickListener(v -> {
                    dialog.dismiss();
                });

                ok.setOnClickListener(v -> {

                    dataList.get(position).setDivision(lou.getText().toString().trim()); //位置

                    List<TAssetAsset> dataList1 = new ArrayList<>();
                    dataList1.add(dataList.get(position));
                    Map<String, String> map = new HashMap<>();
                    map.put("data", new Gson().toJson(dataList1));

                    NetworkUtil.updatePlace(Url.myHttp(), map)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<ResponseBody>() {
                                @Override
                                public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                                }

                                @Override
                                public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                                        adapter.notifyDataSetChanged();
                                }

                                @Override
                                public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                                    showToast("连接超时，请联系开发人员");
                                }

                                @Override
                                public void onComplete() {

                                }
                            });

                    dialog.dismiss();
                });


            }
        });


    }



    private void newSubmit() {

        dataList.clear();
        showDialog("正在上传...");

        for (TAssetAsset for_datum : For_data) {
            for_datum.setCheckResult("2");
        }



        losses_data.addAll(For_data);
        For_data.clear();

        // TODO: 2024/2/22 这个是要走接口把所有类型的数据拼接起来一返回

        dataList.addAll(For_data);
        dataList.addAll(Have_data);
        /*dataList.addAll(profit_data);*/
        dataList.addAll(losses_data);


        for (TAssetAsset profit_datum : profit_data) {
            profit_datum.setCheckDate(nowTime);
        }

        for (TAssetAsset tAssetAsset : dataList) {
            tAssetAsset.setCheckDate(nowTime);
        }

        Map<String, String> yin = new HashMap<>();
        yin.put("data", new Gson().toJson(profit_data));

        yin.put("id", id);

//        NetworkUtil.profitDataSubmit(Url.submit2(), yin)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<ResponseBody>() {
//                    @Override
//                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
//
//                    }
//
//                    @Override
//                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
//                        canDialog();
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });


        Map<String, String> map = new HashMap<>();
        map.put("data", new Gson().toJson(dataList));
        map.put("id", id);


//        NetworkUtil.submit(Url.submit(), map)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Observer<ResponseBody>() {
//                    @Override
//                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
//
//                    }
//
//                    @Override
//                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
//                        submitYes();
//                    }
//
//                    @Override
//                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
//                        showToast("连接失败");
//                        canDialog();
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });


        NetworkUtil.submit1(Url.submit(), map, yin)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Pair<ResponseBody, ResponseBody>>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull Pair<ResponseBody, ResponseBody> responseBodyResponseBodyPair) {
                        try {
                            String profitSubmit = responseBodyResponseBodyPair.first.string();
                            String submit = responseBodyResponseBodyPair.second.string();

                            submitYes();

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        showToast("连接失败");
                        canDialog();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void submitYes() {
        showToast("上传成功!");
        switch (star) {
            case 0:
                switchItem(For_data);
                break;
            case 1:
                switchItem(Have_data);
                break;
            case 2:
                switchItem(profit_data);
                break;
            case 3:
                switchItem(losses_data);
                break;
            default:
                break;
        }


        //待盘点的数量
        For_inventory.setText(For_data.size() + "");
        //已经盘点的数量
        Have_inventory.setText(Have_data.size() + "");
        //盘盈的数量
        inventory_profit.setText(profit_data.size() + "");
        //盘亏的数量
        inventory_losses.setText(losses_data.size() + "");

        canDialog();
    }


    private void switchItem(List<TAssetAsset> list) {

        runOnUiThread(() -> {
            dataList.clear();
            dataList.addAll(list);
            adapter.notifyDataSetChanged();
            finish();
        });



    }


    @SuppressLint("SetTextI18n")
    private void setWaitData() {
        showDialog("加载数据...");


        NetworkUtil.loadData(Url.myHttp(), Since_case.getInstance().getUserId(), id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                        dataList.clear();
                        String result = null;
                        try {
                            result = responseBody.string();

                            TAssetAsset[] tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset[].class);
                            tAssList = Arrays.asList(tAssetAssets);



                            if (tAssList.size() == 0) {
                                showToast("暂无盘点详情");
                                canDialog();
                                return;
                            }

                            for (TAssetAsset bean : tAssList) {
                                if (bean.getCheckResult().isEmpty()) {
                                    For_data.add(bean);
                                }else if (bean.getCheckResult().equals("0")) {
                                    Have_data.add(bean);
                                }else if (bean.getCheckResult().equals("1")) {
                                    profit_data.add(bean);
                                }else if (bean.getCheckResult().equals("2")) {
                                    losses_data.add(bean);
                                }
                            }




                            runOnUiThread(() -> {
                                //待盘点的数量
                                For_inventory.setText(For_data.size() + "");
                                //已经盘点的数量
                                Have_inventory.setText(Have_data.size() + "");
                                //盘盈的数量
                                inventory_profit.setText(profit_data.size() + "");
                                //盘亏的数量
                                inventory_losses.setText(losses_data.size() + "");
                                dataList.addAll(For_data);
                                adapter.notifyDataSetChanged();
                                showToast("加载完成");
                                canDialog();
                            });
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }




                    }

                    @Override
                    public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
                        showToast("连接服务器失败");
                        canDialog();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private void initView() {
//        loadingDialog = new LoadingDialog(this);
//        loadingDialog.setMessage("加载中....");
//        loadingDialog.show();
        runOnUiThread(() -> {


            et_num = (EditText) findViewById(R.id.et_num);
            add_remark = (Button) findViewById(R.id.add);
            recyclerView = (RecyclerView) findViewById(R.id.fragment2_list);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(adapter);
            //待盘点，已盘点，盘盈，盘亏
            losses = (LinearLayout) findViewById(R.id.losses);
            profit = (LinearLayout) findViewById(R.id.profit);
            aFor = (LinearLayout) findViewById(R.id.For);
            have = (LinearLayout) findViewById(R.id.Have);
            imageView = (ImageView) findViewById(R.id.fh);

            ImageView update = (ImageView) findViewById(R.id.rfid_set);
            ImageView imageView1 = (ImageView) findViewById(R.id.rfid_set);
            imageView1.setVisibility(View.GONE);
            imageView.setOnClickListener(v -> {
                newSubmit();
                finish();
            });
            Intent intent = getIntent();
            checkDetailIds = intent.getStringExtra("checkId");
            isEdit = intent.getStringExtra("isEdit");
            LogUtils.d("checkId" + checkDetailIds);
            id = intent.getStringExtra("id");
            scan = (Button) findViewById(R.id.scan);
            btn_rfid = findViewById(R.id.btn_rfid);
            submit = (Button) findViewById(R.id.submit);
            state = intent.getStringExtra("state");
            odd = (TextView) findViewById(R.id.odd);
            odd.setText(intent.getStringExtra("id"));
            createuser = (TextView) findViewById(R.id.createuser);
            createuser.setText(intent.getStringExtra("createUser"));
            sum = (TextView) findViewById(R.id.sum);
            sum.setText(intent.getStringExtra("checkNum"));
            createdate = (TextView) findViewById(R.id.createdate);
            createdate.setText(intent.getStringExtra("createDate"));
            date = (TextView) findViewById(R.id.date);
            For_inventory = (TextView) findViewById(R.id.For_inventory);
            For_inventory.setTextColor(Color.parseColor("#00FF00"));
            et_num.setFocusableInTouchMode(true);
            date.setText("".equals(MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()))&&MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()) == null ? "" : MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()));
            et_num.requestFocus();
            et_num.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    String scanData = et_num.getText().toString();
                    if (TextUtils.isEmpty(scanData)) {
                        return;
                    }
                    et_num.selectAll();
                    handleScanData(scanData);
                }
            });

            selectFragment();

            update.setOnClickListener(v -> {

                updateApp();

            });

        });


    }

    private void updateApp() {



    }



    private void selectFragment() {

        //待盘点的点击方法
        aFor.setOnClickListener(v -> {
            dataList.clear();
            star = 0;
            For_inventory.setTextColor(Color.parseColor("#00FF00"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));
//            dataList.clear();
//            For_data.clear();
            runOnUiThread(() -> {
                dataList.addAll(For_data);
                adapter.notifyDataSetChanged();
            });

        });
        //已经盘点
        Have_inventory = (TextView) findViewById(R.id.Have_inventory);
        have.setOnClickListener(v -> {
            dataList.clear();

            star = 1;
            Have_inventory.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));


            runOnUiThread(() -> {
                dataList.addAll(Have_data);
                adapter.notifyDataSetChanged();
            });
        });
        //盘盈
        inventory_profit = (TextView) findViewById(R.id.inventory_profit);
        profit.setOnClickListener(v -> {
            dataList.clear();
            star = 2;
            inventory_profit.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));

            runOnUiThread(() -> {
                dataList.addAll(profit_data);
                adapter.notifyDataSetChanged();
            });

        });
        inventory_losses = (TextView) findViewById(R.id.inventory_losses);
        losses.setOnClickListener(v -> {
            dataList.clear();
            star = 3;
            inventory_losses.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            runOnUiThread(() -> {
                dataList.addAll(losses_data);
                adapter.notifyDataSetChanged();
            });
        });

        add_remark.setOnClickListener(v -> {
            MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Check.this).builder()
                    .setTitle("请填写备注")
                    .setEditText("");
            myAlertInputDialog.setPositiveButton("确认", v12 -> {
                add_remarks(myAlertInputDialog.getResult());
                myAlertInputDialog.dismiss();
            }).setNegativeButton("取消", v1 -> myAlertInputDialog.dismiss());
            myAlertInputDialog.show();
        });
        scan.setOnClickListener(v -> {
            startQrCode();
            LogUtils.d("调用扫码");
        });

        submit.setOnClickListener(v -> new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Check.this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                //取消：position=-1,确定 position=0
                if (position == 0) {
                    newSubmit();
                }
            }
        }).setCancelable(true).show());

        flag = true;

    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Check.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            handleScanData(scanResult);
        }
        if (requestCode == 2 && resultCode == 6) {
            for (int i = 0; i < profit_data.size(); i++) {
                if (star == 2) {
                    adapter.notifyItemChanged(i);
                }
            }
        }
        if (requestCode == 1 && resultCode == 6) {
            for (int i = 0; i < Have_data.size(); i++) {
                if (star == 1) {
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }

    private void query(final String assetNumber, final String RFID) {
        Map<String, String> map = new HashMap<>();
        map.put("assetNumber", assetNumber);
        map.put("rfid", RFID);
        map.put("checkdetailIds", checkDetailIds);

        MyOkHttp.getInstance().post(query_url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
                showToast("连接服务器失败");
                if (!TextUtils.isEmpty(RFID)) {
                    Check.this.map.remove(RFID);
                }
            }

            @Override
            public void requestComplete() {
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                LogUtils.d(RFID + responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        JSONObject jsonObject = json.getJSONObject("asset");
                        String assetName = jsonObject.getString("assetName");
                        String deptId = jsonObject.getString("deptId");
                        String assetNumber = jsonObject.getString("assetNumber");
                        String userId = jsonObject.getString("userId");
                        String model = jsonObject.getString("model");
                        String type = jsonObject.getString("type");
                        String rfid = jsonObject.getString("rfid");
                        String image = jsonObject.getString("image");
                        if (!TextUtils.isEmpty(image)) {
                            image = "http://" + Url.IP + image;
                        }
                        if (assetNumbers.contains(assetNumber)) return;
                        assetNumbers.add(assetNumber);
//                        profit_data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, rfid));

                        if (star == 2) {

                            runOnUiThread(() -> {
                                adapter.notifyItemInserted(adapter.getItemCount() - 1);
                                Have_inventory.setText(String.valueOf(Have_data.size()));
                                For_inventory.setText(String.valueOf(For_data.size()));
                                inventory_profit.setText(String.valueOf(profit_data.size()));
                                inventory_losses.setText(String.valueOf(losses_data.size()));
                            });
                        }
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                    if (json.getString("state").equals("2")) {
                        showToast("资产不存在");
                    }
                    if (json.getString("state").equals("3")) {
                        showToast("资产待报废");
                    }
                    if (json.getString("state").equals("4")) {
                        showToast("资产未入库");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void add_remarks(final String remark) {
        Map<String, String> map = new HashMap<>();
        map.put("text", remark);
        map.put("checkId", id);
        MyOkHttp.getInstance().post(add_br, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        showToast("提交成功");
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    //扫码
    private synchronized void handleScanData(String scanResult) {
        dataList.clear();




        if (For_data.size() == 0) {
            Map<String, String> map = new HashMap<>();
            map.put("checkId", id);
            map.put("rfid", "");
            map.put("assetNumber", scanResult);

            NetworkUtil.rfidProfit(Url.myHttp(), map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ResponseBody>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                            String result = null;
                            try {
                                result = responseBody.string();
                                Log.d(TAG, "result: " + result);
                                Log.d(TAG, "requestSuccess: " + "成功");
                                if (result == null || result.isEmpty() || result.equals("{}")) {
                                    return;
                                }

                                TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);
                                List<String> quchong = new ArrayList<>();

                                for (TAssetAsset profit_datum : profit_data) {
                                    if (quchong.contains(profit_datum.getRfid())) {
                                        return;
                                    }
                                }


                                tAssetAssets.setUserId(Since_case.getInstance().getUserId());
                                profit_data.add(tAssetAssets);


                                Log.d(TAG, "profit_data: " + new Gson().toJson(profit_data));

                                runOnUiThread(() -> {
                                    //待盘点的数量
                                    For_inventory.setText(For_data.size() + "");
                                    //已经盘点的数量
                                    Have_inventory.setText(Have_data.size() + "");
                                    //盘盈的数量
                                    inventory_profit.setText(profit_data.size() + "");
                                    //盘亏的数量
                                    inventory_losses.setText(losses_data.size() + "");

                                });
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }

                        @Override
                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        }else {

            for (int i = 0; i < losses_data.size(); i++) {

                if (scanResult.equals(losses_data.get(i).getAssetNumber())) {
                    losses_data.get(i).setCheckResult("0");
                    losses_data.get(i).setConcreteNum(losses_data.get(i).getPlanNum());
                    Have_data.add(losses_data.get(i));
                    losses_data.remove(i);
                }
            }

            for (int i = 0; i < For_data.size(); i++) {

                if (scanResult.equals(For_data.get(i).getAssetNumber())) {
                    For_data.get(i).setCheckResult("0");
                    For_data.get(i).setConcreteNum(For_data.get(i).getPlanNum());
                    Have_data.add(For_data.get(i));
                    For_data.remove(i);
                }
            }

            Map<String, String> map = new HashMap<>();
            map.put("checkId", id);
            map.put("rfid", "");
            map.put("assetNumber", scanResult);
            
            NetworkUtil.rfidProfit(Url.myHttp(), map)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<ResponseBody>() {
                        @Override
                        public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseBody responseBody) {
                            String result = null;
                            try {
                                result = responseBody.string();
                                if (result == null || result.isEmpty() || result.equals("{}")) {
                                    return;
                                }
                                TAssetAsset tAssetAssets = MyOkHttp.getInstance().getGson().fromJson(result, TAssetAsset.class);

                                for (TAssetAsset profit_datum : profit_data) {
                                    if (profit_datum.getRfid().equals(tAssetAssets.getRfid())) {
                                        return;
                                    }

                                }
                                tAssetAssets.setUserId(Since_case.getInstance().getUserId());
                                profit_data.add(tAssetAssets);

                                Log.d(TAG, "profit_data: " + new Gson().toJson(profit_data));
                                runOnUiThread(() -> {
                                    For_inventory.setText(For_data.size() + "");
                                    //已经盘点的数量
                                    Have_inventory.setText(Have_data.size() + "");
                                    //盘盈的数量
                                    inventory_profit.setText(profit_data.size() + "");
                                    //盘亏的数量
                                    inventory_losses.setText(losses_data.size() + "");
                                });
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }

                        @Override
                        public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });

        }

    }
    

    public void saoData(List<TAssetAsset> list) {
        runOnUiThread(() -> {
            //待盘点的数量
            For_inventory.setText(For_data.size() + "");
            //已经盘点的数量
            Have_inventory.setText(Have_data.size() + "");
            //盘盈的数量
            inventory_profit.setText(profit_data.size() + "");
            //盘亏的数量
            inventory_losses.setText(losses_data.size() + "");

        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        Log.d(TAG, "onKeyDown: " + keyCode);

        if (keyCode == R50KEYCODE) {
            if (mRfidManager == null) {
                showToast("正在初始化中");
            }else {
                btn_rfid.setText("停止读取");
                setScanStatus(true);
            }
        }
//
//        if (keyCode == 619) {
//            if (iLcUhfProduct != null) {
//                mediaPlayer = MediaPlayer.create(this, R.raw.msg);
//                iLcUhfProduct.StartRead();
//                btn_rfid.setText("停止读取");
//            }
//
//        }
//        if (keyCode == 4) {
//
//            newSubmit();
//
//        }


        return super.onKeyDown(keyCode, event);

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == R50KEYCODE) {
            if (mRfidManager == null) {
                showToast("正在初始化中");
            }else {
                btn_rfid.setText("开始读取");
                setScanStatus(false);
            }

        }
//        if (keyCode == 619) {
//            if (iLcUhfProduct != null) {
//                mediaPlayer.stop();
//                iLcUhfProduct.StopRead();
//                btn_rfid.setText("开始读取");
//            }
//        }
//
        return super.onKeyUp(keyCode, event);
    }

    private Map<String, String> map = new HashMap<>();

    protected void showCustomDialog() {
        // 创建自定义弹窗

    }

    private void notiyDatas(final String s2, final String TID, final String strRSSI) {
        String mapContainStr = null;
        if (!TextUtils.isEmpty(TID)){
            mapContainStr = TID;
        }else {
            mapContainStr = s2;
        }
        final String mapContainStrFinal = mapContainStr;
        Log.d(TAG, "onInventoryTag: EPC: " + s2);

        SoundTool.getInstance(this).playBeep(1);
        readRfid(mapContainStrFinal);

    }

}
